package uk.ac.cam.echo.app;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import uk.ac.cam.echo.messages.Message;
import uk.ac.cam.echo.SafeMessageQueue;

/**
 * @author Tom Smith
 */
public class Writer implements Runnable {
	
	private Socket m_Sock;
	private final SafeMessageQueue<Message> m_SafeMessageQueue;

	public Writer(Socket sock, SafeMessageQueue<Message> queue) throws IOException {
		this.m_Sock = sock;
		this.m_SafeMessageQueue = queue;
	}

	@Override
	public void run() {

		try {
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(this.m_Sock.getOutputStream());

			while (true) {
				Message m = this.m_SafeMessageQueue.take();
				objectOutputStream.writeObject(m);
				objectOutputStream.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}			

}
